<?php
/**
 * @license http://www.gnu.org/licenses/gpl.html GNU GPL, version 3 or later
 * @package FrontPress
 * @subpackage Route
 */

function frontpress_tmpl_load( $template, $args = array(), $template_path = null ) {
	$args = frontpress_tmpl_filter_args( $args );
	do_action_ref_array( 'pre_tmpl_load', array( $template, &$args ) );
	if ( file_exists( FRONTPRESS_TEMPLATE_PATH . 'helper-functions.php' ) )
		require_once FRONTPRESS_TEMPLATE_PATH . 'helper-functions.php';
	$locations = array( FRONTPRESS_TEMPLATE_PATH );
	if ( !is_null( $template_path ) ) {
		array_unshift( $locations, trailingslashit( $template_path ) );
	}
	foreach( $locations as $location ) {
	 	$file = $location . $template . '.php';
		if ( is_readable( $file ) ) {
			extract( $args, EXTR_SKIP );
			include $file;
			break;
		}
	}
	do_action_ref_array( 'post_tmpl_load', array( $template, &$args ) );
}

function frontpress_tmpl_get_output() {
	$args = func_get_args();
	ob_start();
	call_user_func_array( 'frontpress_tmpl_load', $args );
	$contents = ob_get_contents();
	ob_end_clean();
	return $contents;
}

function frontpress_tmpl_header( $args = array() ) {
	if ( isset( $args['http_status'] ) )
		status_header( $args['http_status'] );
	frontpress_tmpl_load( 'header', $args );
}

function frontpress_tmpl_footer( $args = array() ) {
	frontpress_tmpl_load( 'footer', $args );
}

function frontpress_head() {
	wp_print_scripts();
	wp_print_styles();
	do_action( 'frontpress_head' );
}

function frontpress_footer() {
	do_action( 'frontpress_footer' );
}

function frontpress_tmpl_filter_args( $args ) {
	$clean_args = array();
	foreach( $args as $k => $v )
		if ( $k[0] != '_' && $k != 'GLOBALS' && substr( $k, 0, 4 ) != 'HTTP' && substr( $k, 0, 3 ) != 'PHP' )
			$clean_args[$k] = $v;
	return $clean_args;
}

function frontpress_title( $title = null ) {
	static $_title;

	if ( is_null( $title ) ) {
		return apply_filters( 'frontpress_title', $_title );
	} else {
		$_title = esc_html( $title );
	}
}

function frontpress_breadcrumb() {
	static $breadcrumb = array();

	if ( func_num_args() ) {
		$args = frontpress_array_flatten( func_get_args() );
		foreach ( $args as $arg ) {
			if ( is_string( $arg ) ) {
				$breadcrumb[] = $arg;
			} elseif ( is_a( $arg, 'FP_Thing' ) ) {
				if ( is_a( $arg, 'FP_Thing_Breadcrumb_Link' ) ) {
					if ( is_a( $arg, 'FP_Thing_With_Parent' ) ) {
						$_breadcrumb = array();
						while ( $arg && is_a( $arg, 'FP_Thing_Breadcrumb_Link' ) ) {
							$_breadcrumb[] = frontpress_link_get( $arg );

							$arg = is_a( $arg, 'FP_Thing_With_Parent' ) ? $arg->get_parent() : null;
						}
						$breadcrumb = array_merge( $breadcrumb, array_reverse( $_breadcrumb ) );
					} else {
						$breadcrumb[] = frontpress_link_get( $arg );
					}
				} else {
					trigger_error( 'For an FP_Thing to be used in the breadcrumb, it must implement FP_Thing_Breadcrumb_Link', E_USER_WARNING );
				}
			} else {
				trigger_error( 'Could not determine breadcrumb part', E_USER_WARNING );
			}
		}
	} else {
		$breadcrumb = apply_filters( 'frontpress_breadcrumb', $breadcrumb );
		/* translators: separates links in the navigation breadcrumb */
		$separator = '<span class="separator">' . _x( '&rarr;', 'breadcrumb' ) . '</span>';
		return '<span class="breadcrumb">' . implode( $separator, array_filter( $breadcrumb ) ) . '</span>';
	}
}

function frontpress_pagination( $page, $per_page, $objects ) {
	$surrounding = 2;
	$prev = $first = $prev_dots = $prev_pages = $current = $next_pages = $next_dots = $last = $next = '';
	$page = intval( $page )? intval( $page ) : 1;
	$pages = ceil( $objects / $per_page );
	if ( $page > $pages ) return '';
	if ( $page > 1 )
		$prev = '<a href="' . add_query_arg( array( 'page' => $page - 1 ) ) . '" class="previous">&larr;</a>';
	else
		$prev = '<span class="previous disabled">&larr;</span>';
	if ( $page < $pages )
		$next = '<a href="' . add_query_arg( array( 'page' => $page + 1 ) ) . '" class="next">&rarr;</a>';
	else
		$next = '<span class="next disabled">&rarr;</span>';
	$current = '<span class="current">'.$page.'</span>';
	if ( $page > 1 ) {
		$prev_pages = array();
		foreach( range( max( 1, $page - $surrounding ), $page - 1 ) as $prev_page ) {
			$prev_pages[] = '<a href="' . add_query_arg( array( 'page' => $prev_page ) ) . '">' . $prev_page . '</a>';
		}
		$prev_pages = implode( ' ', $prev_pages );
		if ( $page - $surrounding > 1 ) $prev_dots = '<span class="dots">&hellip;</span>';
	}
	if ( $page < $pages ) {
		$next_pages = array();
		foreach( range( $page + 1, min( $pages, $page + $surrounding ) ) as $next_page ) {
			$next_pages[] = '<a href="' . add_query_arg( array( 'page' => $next_page ) ) . '">' . $next_page . '</a>';
		}
		$next_pages = implode( ' ', $next_pages );
		if ( $page + $surrounding < $pages ) $next_dots = '<span class="dots">&hellip;</span>';
	}
	if ( $prev_dots ) $first = '<a href="' . add_query_arg( array( 'page' => 1 ) ) . '">1</a>';
	if ( $next_dots ) $last = '<a href="' . add_query_arg( array( 'page' => $pages ) ) . '">' . $pages . '</a>';
 	$html = <<<HTML
	<div class="paging">
		$prev
		$first
		$prev_dots
		$prev_pages
		$current
		$next_pages
		$next_dots
		$last
		$next
	</div>
HTML;
	return apply_filters( 'frontpress_pagination', $html, $page, $per_page, $objects );
}

function frontpress_link( $url, $text = '' ) {
	echo frontpress_link_get( $url, $text );
}

function frontpress_link_get( $url, $text = '' ) {
	if ( is_a( $url, 'FP_Thing_Breadcrumb_Link' ) )
		return '<a href="' . esc_url( $url->get_url() ) . '">' . esc_html( $url->get_name() ) . '</a>';
	else
		return '<a href="' . esc_url( $url ) . '">' . esc_html( $text ) . '</a>';
}

/**
 * Replaces double line-breaks with paragraph elements.
 *
 * A group of regex replaces used to identify text formatted with newlines and
 * replace double line-breaks with HTML paragraph tags. The remaining
 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
 * or 'false'.
 *
 * @param string $pee The text which has to be formatted.
 * @param int|bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
 * @return string Text which has been converted into correct paragraph tags.
 */
function wpautop($pee, $br = 1) {

	if ( trim($pee) === '' )
		return '';
	$pee = $pee . "\n"; // just to make things a little easier, pad the end
	$pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
	// Space things out a little
	$allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
	$pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
	$pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
	$pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
	if ( strpos($pee, '<object') !== false ) {
		$pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
		$pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
	}
	$pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
	// make paragraphs, including one at the end
	$pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
	$pee = '';
	foreach ( $pees as $tinkle )
		$pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
	$pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
	$pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
	$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
	$pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
	$pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
	$pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
	$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
	$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
	if ($br) {
		$pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<WPPreserveNewline />", $matches[0]);'), $pee);
		$pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
		$pee = str_replace('<WPPreserveNewline />', "\n", $pee);
	}
	$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
	$pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
	if (strpos($pee, '<pre') !== false)
		$pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
	$pee = preg_replace( "|\n</p>$|", '</p>', $pee );

	return $pee;
}
